#include "CycleBuffer.h"

#include <stdint.h>
#include <stdbool.h>
#include <string.h>

// 初始化函数
void CycleBuffer_Init(CycleBuffer_t* cb, uint8_t* buffer, uint16_t capacity) 
{
    cb->buffer = buffer;
    cb->head = 0;
    cb->tail = 0;
    cb->capacity = capacity;
    cb->length = 0;
    cb->overflow = false;
    memset(buffer, 0, capacity); // 初始化清零
}

// 写入数据（支持单字节/批量写入）
bool CycleBuffer_Write(CycleBuffer_t* cb, const uint8_t* buffer, uint16_t len) 
{
    uint16_t remaining = CycleBuffer_GetRemainingSize(cb);
    if (len > remaining) 
    {
        len = remaining; // 限制写入长度
        cb->overflow = true; // 标记溢出
    }

    uint16_t wrap = (cb->tail + len) % cb->capacity;
    if (wrap < cb->tail) 
    {
        // 跨越缓冲区尾部的情况
        uint16_t first_part = cb->capacity - cb->tail;
        memcpy(cb->buffer + cb->tail, buffer, first_part);
        memcpy(cb->buffer, buffer + first_part, len - first_part);
    } else {
        memcpy(cb->buffer + cb->tail, buffer, len);
    }

    cb->tail = wrap;
    cb->length += len;
    return (len > 0);
}

// 读取数据（支持单字节/批量读取）
bool CycleBuffer_Read(CycleBuffer_t* cb, uint8_t* buffer, uint16_t len) 
{
    if (len > cb->length) 
    {
        len = cb->length;
    }
    
    uint16_t wrap = (cb->head + len) % cb->capacity;
    if (wrap < cb->head) 
    {
        // 跨越缓冲区尾部的情况
        uint16_t first_part = cb->capacity - cb->head;
        memcpy(buffer, cb->buffer + cb->head, first_part);
        memcpy(buffer + first_part, cb->buffer, len - first_part);
    } 
    else
    {
        memcpy(buffer, cb->buffer + cb->head, len);
    }

    cb->head = wrap;
    cb->length -= len;
    cb->overflow = false; // 读取后清除溢出标志
    return (len > 0);
}

// 状态查询函数
bool CycleBuffer_IsFull(const CycleBuffer_t* cb)
{
    return (cb->length >= cb->capacity);
}

bool CycleBuffer_IsEmpty(const CycleBuffer_t* cb)
{
    return (cb->length == 0);
}

bool CycleBuffer_IsOverflow(const CycleBuffer_t* cb)
{
    return cb->overflow;
}

// 数据长度查询
uint16_t CycleBuffer_GetCacheSize(const CycleBuffer_t* cb) 
{
    return cb->length;
}

// 剩余空间查询
uint16_t CycleBuffer_GetRemainingSize(const CycleBuffer_t* cb) 
{
    return cb->capacity - cb->length;
}


